#include "adf4351.h"

union DATA_PACKET ADF;

struct PllConfigType PLLConfig = {
    .power = 0,
    .R0 = 0x2fda0000,
    .R1 = 0x08008011,
    .R2 = 0x191f7fc2,
    .R3 = 0x006004b3,
    .R4 = 0x00001404,
    .R5 = 0X00580005
};

//ADF引脚及寄存器配置初始化 频率 2450GHz 输出关断 dBm-4
void ADF4351_Init(void)
{
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
    //通信引脚             CE        CLK        DATA       LE
    GPIO_InitConfig(GPIOA, GPIO_Pin_3|GPIO_Pin_4|GPIO_Pin_5|GPIO_Pin_6, GPIO_Mode_Out_PP, GPIO_Speed_50MHz);
    //MUX_OUT引脚          MUX
    GPIO_InitConfig(GPIOA, GPIO_Pin_7, GPIO_Mode_IPD, GPIO_Speed_50MHz);
    ADF_CE_HIGH;    //使能ADF4351
    delay_ms(1);
    ADF4351_Write(PLLConfig.R5);
    ADF4351_Write(PLLConfig.R4);
    ADF4351_Write(PLLConfig.R3);
    ADF4351_Write(PLLConfig.R2);
    ADF4351_Write(PLLConfig.R1);
    ADF4351_Write(PLLConfig.R0);
}

void ADF4351_Write(uint32_t data)
{
    uint8_t i;
    
    ADF_CLK_LOW;
    ADF_LE_LOW;
    
    delay_us(1);
    
    for(i=0; i<32; i++)
    {
        if(data & 0x80000000)
            ADF_DATA_HIGH;
        else
            ADF_DATA_LOW;
        
        data <<= 1;
        delay_us(1);
        ADF_CLK_HIGH;
        
        delay_us(1);
        ADF_CLK_LOW;
    }
    delay_us(1);
    ADF_LE_HIGH;
    delay_us(1);
}

//设置RF_OUT频率
void ADF4351_Freq(uint32_t freq)
{
    //限制频率的范围
    if(freq<350)   freq = 350;
    if(freq>44000) freq = 44000;
    
    PLLConfig.R4 = 0x00001424;

    //写入R4寄存器
    PLLConfig.R4 |= (uint32_t)PLLConfig.power << 3;
    ADF4351_Write(PLLConfig.R4);
    //将频率写入R0寄存器
    PLLConfig.R0 = freq<<15;
    ADF4351_Write(PLLConfig.R0);
}
/*********************************
RF_OUT_POWER设置
DISABLED = 0,
   dBm-4 = 1,
   dBm-1 = 2,
   dBm+2 = 3,
   dBm+5 = 4,
*********************************/
void ADF4351_Power(uint8_t level)
{
    if(level>4) level = 4;
    if(level)
    {
        level--;
        level |= 4;
    }
    //先将R4寄存器DB4:DB3置零，再赋值
    PLLConfig.R4 &= 0xffffffc7; 
    PLLConfig.R4 |= (uint32_t)level << 3;
    
    ADF4351_Write(PLLConfig.R4);
    ADF4351_Write(PLLConfig.R0);
}
